<?php

class Customer extends Admin_Controller
{
    function __construct()
    {

        parent::__construct();
        error_reporting(E_ALL ^ E_NOTICE);
        $this->load->helper('url_helper');
        $this->load->helper('url');
        $this->load->model('users_model');
        $this->load->model('customer_model');
        $this->load->model('goods_model','goods');
    }
    function checkck($manager_id,$tel){
        $sql = "select count(id) as countid from customer cs WHERE cs.manager_id=".$manager_id." and cs.customer_tel = ".$tel;

        $query = $this->db->query($sql);

        $info =  $query->result_array();

        if($info && $info[0]['countid']>0){
            return false;
        }else{
            return true;
        }
    }

    function check_phone($tel)
    {
        $sql = "select count(1) as total from customer cs WHERE cs.customer_tel = ".$tel;

        $query = $this->db->query($sql);

        $info =  $query->result_array();

        if($info && $info[0]['total']>0){
            return false;
        }else{
            return true;
        }

    }
    //创建客户确定
    function create_confirm(){

        $post = $this->input->post();
        if($post['id'] && $post['name'] && $post['tel']){
            if(!check_name($post['name'])){
                $data['status'] = "fail";
                $data['msg'] = "姓名必须是中文和字母,不能超过10位!";
                $data['data'] = "";
                json_send($data);
                exit;
            }
            // 校验是否已经存在 cj
            if(!$this->checkck($post['id'],$post['tel']))
            {
                $data['status'] = "fail";
                $data['msg'] = "该手机号码已经是您的客户啦！";
                $data['data'] = "";
                json_send($data);
                exit;
            }
            //查找用户信息
            $usr = $this->users_model->get_one($post['id']);
            if(!$usr['name']){
                $data['status'] = "fail";
                $data['msg'] = "你的姓名为空，无法创建客户！";
                $data['data'] = "";
                json_send($data);
                exit;
            }
            //获取商城客户信息
            $url = $this->config->item("shop_base_url")."citymanagerapi/customer_detail_mobile/";
            $data1['key'] = md5_key();
            $data1['tel'] = $post['tel'];
            $get_data = curl_request($url,$data1);
            $get_data = json_decode($get_data);
            // 使用新account
            $data_1['manager_account'] = $usr['name'];
            $data_1['name'] = $post['name'];
            $data_1['password'] = $this->customer_model->get_pwd($post['id']);

            if ($get_data->data){
                $data_1['customer'] = $get_data->data;
            }else{
                $data_1['customer'] = "";
            }
            $data['data'] = $data_1;
            $data['save_key'] = uniqid();
            $data['status'] = "success";
            $data['msg'] = "成功";

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }

    //创建
    function create(){
        $post = $this->input->post();
        if($post['id'] && $post['name'] && $post['tel'] && $post['account'] && $post['password']){
            // 校验是否已经存在 cj
            if(!$this->checkck($post['id'],$post['tel']))
            {
                $data['status'] = "fail";
                $data['msg'] = "该手机号码已经是您的客户啦！";
                $data['data'] = "";
                json_send($data);
                exit;
            }
            // 手机号唯一性校验 cj
            if(!$this->check_phone($post['tel']))
            {
                $data['status'] = "fail";
                $data['msg'] = "该手机号码已存在！";
                $data['data'] = "";
                json_send($data);
                exit;
            }
            // 当前经理信息 cj
            $manager_info = $this->db->where(["id"=>$post['id']])->get("manager")->row_array();
            $customer_id = $post['shop_customer_id'];
            //本地添加的数据
            $data_arr = array(
                "customer_name"=>$post['name'],
                "customer_tel"=>$post['tel'],
                "customer_email"=>$post['email'],
                "company"=>$post['company'],
                "position"=>$post['job'],
                "manager_id"=>$post['id'],
                "created_at"=>date("Y-m-d H:i:s"),
                "pic_path"=>$this->customer_model->create_pic($post['name']),
                "password"=>$post['password'],
            );
            //验证下格式
            $rs = $this->customer_model->validate($data_arr);
            if($rs['status']=='fail'){
                json_send($rs);exit;
            }
            if($customer_id){
                $data_arr['shop_customer_id'] = $customer_id;
            }
            //如果重复，重新获取
            if($this->customer_model->is_has_pwd($post['id'],$post['password'])){
                $data_arr['password'] = $this->customer_model->get_pwd($post['id']);
            }
            // $post['account'] 存入到username 新增字段
            $data_arr['username'] = $post['account'];

            //给商城的客户数组
            $customer = array(
                "name"=>$post['name'],
                "tel"=>$post['tel']
            );
            //如果存在则存到客户数组
            $customer['email']= $post['email']?$post['email']:"";
            $customer['company'] =  $post['company']? $post['company']:"";
            $customer['position'] = $post['position']? $post['position']:"";
            //开启事务
            $this->db->trans_begin();
            //创建本地客户
            $bool = $this->db->insert("customer",$data_arr);
            if ($this->db->affected_rows()){
                $insert_id =$this->db->insert_id();
                $now = date("Y-m-d h:i:s");
                $mg_id = $post['id'];
                $his_string = "insert into customer_bind_history (manager_id,customer_id,start_time) VALUES ($mg_id,$insert_id,'".$now."')";
                $bool = $this->db->query($his_string);
            }
            if ($insert_id){
                //同步到商城
                $url = $this->config->item("shop_base_url")."citymanagerapi/sync_customer/";
                $data1['key'] = md5_key();
                $customer['tel'] = $post['tel'];
                $data1['account'] = $post['account'];
                // 经理账号也要传
                $data1['saler_account'] = $manager_info['name'];
                $data1['password'] =$data_arr['password'];
                $data1['customer_id'] = $insert_id;

                if ($customer_id){
                    $data1['uid'] = $customer_id;
                }else{
                    $data1['customer'] = json_encode($customer);
                }
                //发送数据
                $get_data = curl_request($url,$data1);
                $get_data = json_decode($get_data);
                if ($get_data->code==200){
                    if(!$customer_id && $get_data->data->uid){
                        $upd_arr['shop_customer_id'] = $get_data->data->uid;
                    }
                    if($get_data->data->pic_path){
                        $upd_arr['shop_customer_id'] = $get_data->data->uid;
                    }
                    if($upd_arr){
                        $this->db->where(array("id"=>$insert_id))->update("customer",$upd_arr);
                    }
                    $data['status'] = "success";
                    $data['msg'] = "创建成功";
                    $data['data'] = "";
                    //app客户id
                    $cus_id = $insert_id;
                    //处理调价信息
                    if($post['save_key']){
                        $unit_price =  $this->goods->get_temp_unit_price($post['save_key']);
                        if($unit_price){
                            $unit_price_json = json_encode($unit_price);
                            $adjust_rs = $this->goods->adjust_unit_price($cus_id , $unit_price_json);
                            if ($adjust_rs['status']=="fail"){
                                $data['msg'].=",".$adjust_rs['msg'];
                            }
                            $this->db->delete('key_value',array('key'=>$post['save_key']));
                        }

                    }
                    if($post['all_ratio']){
                        $adjust_rs = $this->goods->adjust_all_price($cus_id ,$post['all_ratio']);
                        if ($adjust_rs['status']=="fail"){
                            $data['msg'].=",".$adjust_rs['msg'];
                        }
                    }
                    if($post['record']){
                        $add_data = array("customer_id"=>$cus_id,"manager_id"=>$post['id'],"content"=>$post['record'],"created_at"=>date("Y-m-d H:i:s"));
                        $bool = $this->db->insert("customer_record",$add_data);
                    }
                    $this->db->trans_commit();
                    //发短信
                    $mg = $this->users_model->get_one($post['id']);
                    $msg = "【文具1号】尊敬的".$post['name']."客户，销售经理".$mg['name']."（".$mg['tel']."）为您创建专属采购帐号：".$post['account']."，密码：".$post['password']."。办公用品阳光采购，就上www.wjyh.com";
                    // 重写发短信
                    $this->load->library('message', '', 'mylib');
                    $message_lib = $this->mylib;
                    // end
                    $bool_dx = $message_lib->send_msg($post['tel'],$msg);
                    if ($bool_dx['status'] != 'success'){
                        $data['msg'].="，".$bool_dx['msg'];
                    }
                }else{
                    $this->db->trans_rollback();
                    $data['status'] = "fail";
                    $data['msg'] = $get_data->msg;
                    $data['data'] = "";
                }
            }else{
                $data['status'] = "fail";
                $data['msg'] = "创建失败";
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);

    }


    //添加跟近记录
    function add_record(){
        $post = $this->input->post();
        if($post['customer_id']  && $post['content'] && $post['manager_id']){
            $this->checkrole($post['customer_id'],$post['manager_id']);
            $add_data = array("customer_id"=>$post['customer_id'],"manager_id"=>$post['manager_id'],"content"=>$post['content'],"created_at"=>date("Y-m-d H:i:s"));
            $bool = $this->db->insert("customer_record",$add_data);
            if ($bool && $this->db->affected_rows()){
                $data['status'] = "success";
                $data['msg'] = "添加成功";
                $data['data'] = "";
            }else{
                $data['status'] = "fail";
                $data['msg'] = "添加失败";
                $data['data'] = "";
            }

        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }


    //获取跟进记录 cj
    function records_list(){
        $manager_id = $_GET['manager_id'];
        $customer_id = $_GET['customer_id'];
        if ($manager_id && $customer_id){
            // 判断权限
            $this->checkrole($customer_id,$manager_id);
            $desc['page'] = $_GET['page']?(int)$_GET['page']:1;
            $desc['psize'] = $_GET['psize']?(int)$_GET['psize']:3;
            $limit_from = ($desc['page']-1)*$desc['psize'];
            $sql = "SELECT
                            *
                        FROM
                            customer_record
                        WHERE
                           1 = 1
                        AND manager_id = ".$manager_id." 
                        AND customer_id = ".$customer_id."
                        ORDER BY created_at DESC";
            $sql.=" limit ".$limit_from.",".$desc['psize'];
            $info = $this->db->query($sql)->result_array();
            if ($info){
                $data['data'] = $info;
            }else{
                $data['data'] = "";
            }
            $data['msg'] = "获取成功";
            $data['status']= "success";
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }

        json_send($data);
    }

    //获取跟进记录
    function records(){
        $id = $_GET['customer_id'];
        if ($id){
            $info = $this->db->where(array("customer_id"=>$id))->get("customer_record")->result_array();
            if ($info){
                $data['data'] = $info;
            }else{
                $data['data'] = "";
            }
            $data['msg'] = "获取成功";
            $data['status']= "success";
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }

        json_send($data);
    }
    //单价浮动
    function unit_price_upd(){
        if($_GET['customer_id'] && $_GET['price'] && $_GET['product_id']){
            //同步到商城
            $url = $this->config->item("shop_base_url")."citymanagerapi/sync_single_product/";
            $data1['key'] = md5_key();
            $data1['price'] = $_GET['price'];
            $data1['product_id'] = $_GET['product_id'];
            $data1['customer_id'] =$_GET['customer_id'];
            //发送数据
            $get_data = curl_request($url,$data1);
            $get_data = json_decode($get_data);
            if ($get_data->code==200){
                $data['msg'] = "调价成功";
                $data['status'] = "success";
                $data['data'] = "";
            }else{
                $data['msg'] = $get_data->msg;
                $data['status'] = "fail";
                $data['data'] = "";
            }
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }
    //总价浮动
    function all_price_upd(){
        if($_GET['customer_id'] && $_GET['ratio']){
            //同步到商城
            $url = $this->config->item("shop_base_url")."citymanagerapi/sync_all_product/";
            $data1['key'] = md5_key();
            $data1['ratio'] = $_GET['ratio'];
            $data1['customer_id'] =$_GET['customer_id'];
            //发送数据
            $get_data = curl_request($url,$data1);
            $get_data = json_decode($get_data);
            if ($get_data->code==200){
                $data['msg'] = "调价成功";
                $data['status'] = "success";
                $data['data'] = "";
            }else{
                $data['msg'] = $get_data->msg;
                $data['status'] = "fail";
                $data['data'] = "";
            }
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }
//
//    function test(){
////        echo $this->customer_model->get_pwd(48);
//        $this->db->trans_begin();
//        $this->db->query("update customer set customer_email='1116' WHERE  id=1");
//        if (1)
//        {
//            $this->db->trans_rollback();
//        }
//        else
//        {
//            $this->db->trans_commit();
//        }
//
//
//    }

    //删除跟进记录 add by wxchendm 2017-9-6
    public function record_delete(){
      $post = $this->input->post();
      // $post['id'] = 4;
      if (isset($post['id']) && isset($post['manager_id'])){
          // 判断是否存在绑定关系
          $manager = $this->db->where(["id"=>$post['id'],"manager_id"=>$post['manager_id']])->get("customer_record")->row_array();
          if(!$manager)
          {
              $data['status'] = "fail";
              $data['msg'] = "没有权限";
              $data['data'] = "";
              json_send($data);
              exit();
          }
          $res = $this->db->delete('customer_record',array('id'=>$post['id']));
          if ($res){
              $data['status'] = "success";
              $data['msg'] = "删除成功";
              $data['data'] = "";
          }else{
              $data['status'] = "fail";
              $data['msg'] = "删除失败!";
              $data['data'] = "";
          }
      }else{
          $data['status'] = "fail";
          $data['msg'] = "参数错误";
          $data['data'] = "";
      }
      // echo '<pre/>';print_r($data);exit;
      echo json_encode($data);
    }


    // 判断权限 cj
    public function checkrole($customer_id,$manager_id)
    {
        $manager = $this->db->where(["id"=>$customer_id,"manager_id"=>$manager_id])->get("customer")->row_array();
        if(!$manager)
        {
            $data['status'] = "fail";
            $data['msg'] = "没有权限";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        return true;
    }
    //同步商城客户信息
    function sync_info(){
        $post = $this->input->post();
        if($post['shop_customer_id'] && $post['info']){
            $info = json_decode($post['info'],true);
            if($info['pic_path']){
                $map['shop_customer_id'] = $info['shop_customer_id'];
//                $info['name']?$upd['customer_name']=$info['name']:1;
//                $info['tel']?$upd['customer_tel']=$info['tel']:1;
                $info['pic_path']?$upd['pic_path']=$info['pic_path']:1;
                $this->db->where($map)->update("customer",$upd);
                if($this->db->affected_rows()){
                    $data['status'] = "success";
                    $data['msg'] = "同步成功";
                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "同步失败";
                }

            }else{
                $data['status'] = "fail";
                $data['msg'] = "无修改信息";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
        }
        json_send($data);
    }

    // 客户所属经理信息
    function customer_belong_manager(){
        $id = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';
        $shop_customer_id = isset($_GET['shop_customer_id']) ? $_GET['shop_customer_id'] : '';
        if ($id){
            $info = $this->db->where(array("id"=>$id))->get("customer")->row_array();
            $manager_id = $info['manager_id'];
            $manager_info = $this->db->where(array("id"=>$manager_id))->get("manager")->row_array();
            if ($manager_info){
                $manager_info['pic_path'] = $manager_info['pic_path']?$this->config->item("upload_url").$manager_info['pic_path']:"";
                $manager_info['pic'] = $manager_info['pic']?$this->config->item("upload_url").$manager_info['pic']:"";
                unset($manager_info['password']);
                unset($manager_info['pic']);
                unset($manager_info['registration_id']);
                unset($manager_info['wage']);
                unset($manager_info['phone']);
                unset($manager_info['performance_wage']);
                unset($manager_info['eligible_date']);
                unset($manager_info['certification_message']);
                $data['data'] = $manager_info;
            }else{
                $data['data'] = "";
            }
            $data['msg'] = "获取成功";
            $data['status']= "success";
        }
        elseif ($shop_customer_id)
        {
            $info = $this->db->where(array("shop_customer_id"=>$shop_customer_id))->get("customer")->row_array();
            $manager_id = $info['manager_id'];
            $manager_info = $this->db->where(array("id"=>$manager_id))->get("manager")->result_array();
            if ($manager_info){
                $manager_info['pic_path'] = $manager_info['pic_path']?$this->config->item("upload_url").$manager_info['pic_path']:"";
                $manager_info['pic'] = $manager_info['pic']?$this->config->item("upload_url").$manager_info['pic']:"";
                unset($manager_info['password']);
                unset($manager_info['pic']);
                unset($manager_info['registration_id']);
                unset($manager_info['wage']);
                unset($manager_info['phone']);
                unset($manager_info['performance_wage']);
                unset($manager_info['eligible_date']);
                unset($manager_info['certification_message']);
                $data['data'] = $manager_info;
            }else{
                $data['data'] = "";
            }
            $data['msg'] = "获取成功";
            $data['status']= "success";
        }
        else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }

        json_send($data);
    }

    function create_all_pic(){
        $customer = $this->db->get("customer")->result_array();
        foreach ($customer as $v){
            $pic = strtolower($this->customer_model->create_pic($v['customer_name']));
            $this->db->where(array("id"=>$v['id']))->update("customer",array("pic_path"=>$pic));
        }

    }

    // 工作台获取客户信息，上级和上上级信息
    public function get_customer_info_api()
    {
        $post = $this->input->post();
        if(isset($post['shop_customer_id']) && $post['shop_customer_id'])
        {
            $sql = "select c.username, c.manager_id,c.customer_name,c.customer_tel AS tel,c.customer_email as email,c.company,c.position,c.created_at,c.pic_path,c.discount,c.adjustments, m.tel AS m_tel,m.name AS mananger_name,m.pic_path AS manager_pic_pth,m.identity AS manager_identity,m.gender AS manager_gender from customer AS c LEFT JOIN manager AS m ON c.manager_id = m.id WHERE c.shop_customer_id = ".$post['shop_customer_id'];
            $customer_info = $this->db->query($sql)->row_array();
            if($customer_info)
            {
                $sql2 = "select m.id AS parent_id, m.name AS parent_name, m.identity AS parent_identity, m.tel as parent_phone from manager_bind AS mb LEFT JOIN manager AS m ON mb.parent_id = m.id WHERE mb.manager_id = ".$customer_info['manager_id'];
                $parent_info = $this->db->query($sql2)->row_array();
                $data['status'] = "success";
                $data['msg'] = "";
                $parent_info=$parent_info?$parent_info:[];
                $data['data'] = array_merge($customer_info,$parent_info);

            }else{
                $data['status'] = "fail";
                $data['msg'] = "不存在的";
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "缺少参数";
            $data['data'] = "";
        }

        json_send($data);
    }

}